<template>
  <div class="search-container scroll-container">
    <!-- 批量操作 -->
    <OnlineBatch
      v-show="showSelect"
      :songs="curList"
      :song-id-mapper="songIdMapper"
      @close-select="closeSelect"
    ></OnlineBatch>
    <!-- 顶部歌手搜索结果 -->
    <div
      class="result-singer"
      v-show="firstSinger.name"
      @click="
        router.push({
          name: 'artist',
          query: {
            id: firstSinger.id,
            score: firstSinger.score
          }
        })
      "
    >
      <img :src="firstSinger.avatar" class="left-singer" />
      <div class="right-singer">
        <h4 class="singer-name">歌手{{ firstSinger.name }}</h4>
        <p class="singer-info">
          <span>专辑:{{ firstSinger.albumSize }}</span>
          <span>视频:{{ firstSinger.mvSize }}</span>
        </p>
      </div>
    </div>
    <Tab
      v-show="!showSelect"
      @getActive="getActive"
      active="song"
      class="search-tab"
    >
      <template #content>
        <el-tab-pane label="歌曲" name="song">
          <div class="header-operation">
            <PlayButton :songs="curList" />
            <CommonButton icon="&#xe761;" @click="loveAll" name="全部收藏" />
            <CommonButton
              icon="&#xe617;"
              @click="showSelect = !showSelect"
              name="批量操作"
            />
          </div>
          <!-- 歌单 -->
          <SongTable
            :songs="curList"
            :page-size="pageSize"
            :song-id-mapper="songIdMapper"
          />
          <!-- 分页器 -->
          <Pagination
            v-show="pageSize < total"
            :cur-page="curPage"
            :page-size="pageSize"
            :total="total"
            @page-change="pageChange"
          />
        </el-tab-pane>
        <el-tab-pane label="视频" name="video">
          <Loading :is-loading="isLoading" />
          <NoResult v-show="needNoSearch[0]" text="暂无搜索结果" />
          <ArtistMv
            :mvs="videoResult"
            :show-pagination="true"
            v-show="!needNoSearch[0]"
          />
        </el-tab-pane>
        <el-tab-pane label="MV" name="mv">
          <Loading :is-loading="isLoading" />
          <NoResult v-show="needNoSearch[1]" />
          <ArtistMv
            :mvs="mvResult"
            :show-pagination="true"
            v-show="!needNoSearch[1]"
          />
        </el-tab-pane>
        <el-tab-pane label="专辑" name="album">
          <Loading :is-loading="isLoading" />
          <NoResult v-show="needNoSearch[2]" text="暂无搜索结果" />
          <!-- 专辑暂无 -->
        </el-tab-pane>
        <el-tab-pane label="电台" name="radio">
          <Loading :is-loading="isLoading" />
          <NoResult v-show="needNoSearch[3]" text="暂无搜索结果" />
          <ArtistPlaylist
            :playlists="radioResult"
            :show-pagination="true"
            type="radio"
            v-show="!needNoSearch[3]"
          />
        </el-tab-pane>
      </template>
    </Tab>
  </div>
</template>

<script setup lang="ts">
import OnlineBatch from '@/components/batch/online-batch/index.vue'
import PlayButton from '@/components/button/play-button/index.vue'
import CommonButton from '@/components/button/common-button/index.vue'
import SongTable from '@/components/table/song-table/index.vue'
import Pagination from '@/components/pagination/index.vue'
import { Album, Artist, MV, Playlist, Song } from '@/model'
import { computed, inject, reactive, ref, Ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Tab from '@components/tab/index.vue'
import useUserStore from '@/store/user'
import { storeToRefs } from 'pinia'
import { Loading, NoResult } from '@/components/result'
import { ArtistMv, ArtistPlaylist } from '@/components/datalist'
import useConfigStore from '@/store/config'
import {
  elMessage,
  getMusicInfos,
  getMusicUrls,
  getRequest,
  getTheme
} from '@/utils'
import useFooterStore from '@/store/footer'
import { searchMusic } from '@/api'
import { getMusicDetail } from '@/api'
import { elMessageType } from '@/model/enum'

// 配置主题
const config = useConfigStore()
const { bgMode } = storeToRefs(config)
const fontGray = inject('fontGray')

const boxShadow = getTheme().get('shadow')
const fontColor = getTheme().get('fontColor')
const themeColor = getTheme().get('themeColor')
// 页面第一次加载的动画
const first = inject('firstLoading') as Ref<boolean>

const singerBg = computed(() => {
  if (fontColor?.value == '#ffffff') {
    return 'rgba(30, 30, 30, 0.2)'
  } else {
    return 'rgba(220, 220, 220, 0.25)'
  }
})
const buttonBg = computed(() => {
  if (fontColor?.value == '#ffffff') {
    return 'rgba(30, 30, 30, 1)'
  } else {
    return 'rgba(220, 220, 220, 0.8)'
  }
})

const router = useRouter()

const user = useUserStore()
const { loveMusicId, loveSongs } = storeToRefs(user)
const footer = useFooterStore()
// 获取搜索关键词
const route = useRoute()
const keyWord = route.query.keyWord + ''

// 当前活跃的tab
const activeTab = ref<string>('song')

// 用于分页
const curPage = ref<number>(1)
// 一页的数据
const pageSize = ref<number>(30)
// 是否加载选择框进入批量操作模式
const showSelect = ref<boolean>(false)
// 音乐搜索的结果
const musicResult = reactive<Song[]>([])
// 歌曲总数
const total = ref<number>(musicResult.length)
// 加载数据的动画
const isLoading = ref<boolean>(false)
// 是否展示占位图片
const needNoSearch = reactive<boolean[]>([false, false, false, false])
// 视频搜索结果
const videoResult = reactive<MV[]>([])
// mv搜索结果
const mvResult = reactive<MV[]>([])
// 电台搜索结果
const radioResult = reactive<Playlist[]>([])
// 专辑搜索结果
const albumResult = reactive<Album[]>([])

// 喜欢所有的歌曲
const loveAll = () => {
  musicResult.forEach((item) => {
    item.isLove = true
    const index = loveMusicId.value.get(item.id)
    if (index == undefined) {
      loveSongs.value.push(item)
    }
  })
}

// 歌曲id与index对应的map
// 键：歌曲id 键值:index
const songIdMapper = computed(() => {
  return new Map(musicResult.map((item, index) => [item.id, index]))
})

// 当前展示的歌曲列表
const curList = computed(() => {
  return musicResult.slice(
    (curPage.value - 1) * pageSize.value,
    curPage.value * pageSize.value
  )
})

// 关闭批量操作
const closeSelect = (close: boolean) => {
  showSelect.value = close
}

// 歌手搜索的结果
const singerResult = reactive<Artist[]>([])
// 第一位歌手，用于页面顶部展示
const firstSinger = computed(() => {
  return singerResult.length > 0
    ? singerResult[0]
    : ({
        name: '',
        avatar: '',
        id: '',
        score: '',
        albumSize: '',
        mvSize: ''
      } as Artist)
})

// 页码改变时
const pageChange = (page: number) => {
  curPage.value = page
}
// 根据当前活跃tab请求搜索结果
const getActive = (active: string) => {
  activeTab.value = active
  if (active == 'video' && videoResult.length == 0) {
    getRequest(async () => {
      try {
        const response: any = await searchMusic(1014, 100, keyWord)
        const {
          result: { videos }
        } = response
        if (videos && videos.length > 0) {
          videos.forEach((item: any) => {
            const { vid, title, coverUrl, creator, playTime } = item
            videoResult.push({
              id: vid,
              name: title,
              image: coverUrl,
              artist: creator[0].userName,
              playCount: playTime
            })
          })
        }
      } catch (err: any) {
        elMessage(elMessageType.ERROR, err.message)
      }
      // 关闭动画
      isLoading.value = false
      // 判断是否需要占位图片
      needNoSearch[0] = videoResult.length == 0
    }, isLoading)
  } else if (active == 'mv' && mvResult.length == 0) {
    getRequest(async () => {
      try {
        const response: any = await searchMusic(1004, 100, keyWord)
        const {
          result: { mvs }
        } = response
        if (mvs && mvs.length != 0) {
          mvs.forEach((item: any) => {
            const { id, name, cover, artistName, playCount } = item
            mvResult.push({
              id,
              name,
              image: cover,
              artist: artistName,
              playCount
            })
          })
        }
      } catch (err: any) {
        elMessage(elMessageType.ERROR, err.message)
      }
      // 关闭动画
      isLoading.value = false
      // 判断是否需要占位图片
      needNoSearch[1] = mvResult.length == 0
    }, isLoading)
  } else if (active == 'album' && albumResult.length == 0) {
    console.log('没有专辑')
  } else if (active == 'radio' && radioResult.length == 0) {
    getRequest(async () => {
      try {
        const response: any = await searchMusic(1009, 100, keyWord)
        const {
          result: { djRadios }
        } = response
        if (djRadios && djRadios.length > 0) {
          djRadios.forEach((item: any) => {
            const { id, name, picUrl, playCount } = item
            radioResult.push({
              name,
              id,
              image: picUrl,
              playCount,
              creator: { nickname: '', avatarUrl: '' },
              tag: [],
              description: ''
            })
          })
        }
      } catch (err: any) {
        elMessage(elMessageType.ERROR, err.message)
      }
      // 关闭动画
      isLoading.value = false
      // 判断是否需要占位图片
      needNoSearch[3] = radioResult.length == 0
    }, isLoading)
  }
}

getRequest(async () => {
  try {
    const responses: any[] = await Promise.all([
      searchMusic(1, 100, keyWord),
      searchMusic(100, 100, keyWord)
    ])
    responses.forEach(async (response, index) => {
      // 获取音乐搜索结果
      if (index == 0) {
        const {
          result: { songs }
        } = response
        // 获取搜索歌曲
        if (songs && songs.length > 0) {
          // 获取歌曲id
          const ids = songs.map((item: any) => item.id).join(',')
          // 重新获取图片
          const dResponse: any = await getMusicDetail(ids)
          const { songs: muiscs } = dResponse
          muiscs.forEach((item: any) => {
            getMusicInfos([] as string[], musicResult, item)
          })
          // 获取搜索歌曲的urls
          getMusicUrls(ids, musicResult)
          // 初始化歌曲喜欢的状态
          user.initLoveMusic(musicResult)
        }
      } // 获取搜索歌手
      else if (index == 1) {
        const {
          result: { artists }
        } = response
        console.log(artists)
        if (artists && artists.length > 0) {
          artists.forEach((item: any) => {
            const { id, name, picUrl, accountId, albumSize, mvSize } = item
            singerResult.push({
              id,
              name,
              avatar: picUrl,
              score: accountId,
              albumSize,
              mvSize
            })
          })
        }
        needNoSearch[4] = singerResult.length == 0
      }
    })
  } catch (err: any) {
    elMessage(elMessageType.ERROR, err.message)
  }
  //   关闭动画
  first.value = false
}, first)
</script>

<style lang="less" scoped>
@font-color-gray: v-bind(fontGray);
@font-color-green: v-bind(themeColor);
@font-color: v-bind(fontColor);
@box-shadow: v-bind(boxShadow);
@color-white: #ffffff;
@theme-color: v-bind(themeColor);
.pagination-container {
  margin: 10px 0;
}
.search-container {
  padding-top: 0 !important;
  padding-bottom: 0 !important;

  .result-singer {
    cursor: pointer;
    width: 82vw;
    margin: 5px 0;
    display: flex;
    padding: 15px 0 20px 1vw;
    background-color: v-bind(singerBg);
    align-items: center;
    border-radius: 5px;
    position: relative;
    .left-singer {
      height: 70px;
      width: 70px;
      border-radius: 50%;
      box-shadow: @box-shadow;
    }

    .el-button {
      height: 30px;
      width: 100px;
      font-size: 12px;
      border-radius: 15px;
      position: absolute;
      right: 30px;
      background-color: v-bind(buttonBg);
      &:deep(span) {
        color: @font-color;
      }
      box-shadow: none;
      &:deep(.iconfont) {
        font-size: 15px;
      }
      &:active {
        background-color: rgba(230, 230, 230, 0.4);
      }
    }
    .right-singer {
      margin-left: 20px;
      .singer-name {
        font-size: 17px;
        letter-spacing: 1px;
        color: @font-color;
        font-weight: 530;
        &:hover {
          color: @theme-color;
        }
      }
      .singer-info {
        margin-top: 5px;
        font-size: 13px;
        color: @font-color-gray;
        span {
          &:last-child {
            margin-left: 15px;
          }
          &:hover {
            color: @theme-color;
          }
        }
      }
    }
  }

  .loading {
    position: absolute;
    top: 0;
    z-index: 100;
  }
  .mv {
    width: 80vw;
    &:deep(.mv-simi) {
      width: 80vw;
    }

    &:deep(.mv-recommend .mask) {
      width: 232px;
    }
    &:deep(.mv-recommend .image) {
      width: 232px;
    }
    &:deep(.mv-recommend .singer) {
      width: 232px;
    }
    &:deep(.mv-recommend .title-name) {
      width: 232px;
    }
  }

  .singer-container {
    &:deep(.singer-list) {
      width: 80vw;
    }

    &:deep(.singer .el-image) {
      width: 187.5px;
    }
    &:deep(.singer span) {
      width: 187.5px;
    }
  }

  .playlist {
    @common: 186.5px;
    &:deep(.content) {
      width: 80vw;
    }
    &:deep(.content .list .mask) {
      width: @common;
      height: @common;
    }
    &:deep(.content .list .playcount) {
      top: 155px;
    }
    &:deep(.content .list .el-image) {
      width: @common;
      height: @common;
    }
    &:deep(.content .list .name) {
      width: @common;
    }
  }

  .header-operation {
    margin: 15px 0;
    .el-button {
      font-size: 13px;
      width: 125px !important;
    }
    .play {
      background-color: @theme-color;
      color: @color-white;
    }
  }

  .search-tab {
    &:deep(.el-tab-pane) {
      position: relative;
    }
    &:deep(.el-tabs__active-bar) {
      left: 5.5px;
    }
  }
}
</style>
